package com.alex.server.service.impl;

import com.alex.server.domain.Chapter;
import com.alex.server.domain.ChapterExample;
import com.alex.server.dto.ChapterDto;
import com.alex.server.dto.ChapterPageDto;
import com.alex.server.dto.PageDto;
import com.alex.server.mapper.ChapterMapper;
import com.alex.server.service.IChapterService;
import com.alex.server.util.CopyUtil;
import com.alex.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class ChapterServiceImpl implements IChapterService {

    @Autowired
    private ChapterMapper mapper;

    @Override
    public PageDto pageList(ChapterPageDto chapterPageDto) {
        PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        if (!StringUtils.isEmpty(chapterPageDto.getCourseId())) {
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }
        List<Chapter> chapterList = mapper.selectByExample(chapterExample);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());
        List<ChapterDto> chapterDtoList = CopyUtil.copyList(chapterList, ChapterDto.class);
        chapterPageDto.setList(chapterDtoList);
        return chapterPageDto;
    }

    @Override
    public void addCourse(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (StringUtils.isEmpty(chapterDto.getId())){
            this.insert(chapter);
        } else {
            this.update(chapter);
        }
    }

    @Override
    public void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        mapper.insert(chapter);
    }

    @Override
    public void update(Chapter chapter) {
        mapper.updateByPrimaryKey(chapter);
    }

    @Override
    public void delete(String id) {
        mapper.deleteByPrimaryKey(id);
    }

}
